import sys
import csv
import logging

from cultureday.models import BusRoute, BusStop, BusStopRoute
from cultureday.management.base import MultiItemJob

class Command(MultiItemJob):
    
    filename = None
    f = None
    help = u'takes a list of bus stops from ... and adds them to the database'

    def pre_process(self, *args, **options):
        if args:
            self.f = open(args[0])
        else:
            self.f = sys.stdin
            
#        lines = f.readlines()
#        print lines;
            
        self.count=0
        super(MultiItemJob, self).pre_process()
            
    def items(self):
        csvfile = self.f
#        dialect = csv.Sniffer().sniff(csvfile.read(1024))
#        csvfile.seek(0)
        reader = csv.reader(csvfile, delimiter=",")
        return reader
    
    def process(self, item):
#        if self.count > 100:
#            return
        false_string = ''
        self.count = self.count+1
        route = item[0]
        run = item[1]
        seq = item[2]
        stop = item[3]
        site = item[4]
        feature = item[5]
        town = item[6]
        locality = item[7]
        area = item[8]
        easting = item[10]
        northing = item[11]
        
        if route is False:
            false_string += 'route is False,'
        if run is False:
            false_string += 'run is False,'
        if seq is False:
            false_string += 'seq is False'
        if stop is False:
            false_string += 'stop is False'
        if false_string:
            print 'For line %s, note the following: %s!' % (self.count, false_string)
            return
        
        busroute, created = BusRoute.objects.get_or_create(
            route_num=route
        )
        busstop, created = BusStop.objects.get_or_create(
            number = stop,
            sitename = site,
            feature_location = feature,
            town_name = town, 
            locality_name = locality,
            area_code = area,
            easting = easting,
            westing = northing
        )
        
        busstoproute, created = BusStopRoute.objects.get_or_create(
            bus_stop = busstop,
            bus_route = busroute,
            run_num = run,
            sequence_num = seq
        )
        
        
